<template>
  <span :style="field.errMsgStyle"
        :class="[commonClasses.commonErrMsgClass, field.errMsgClass]"
        v-if="!errMsgHidden">{{message}}</span>
</template>

<script>
  import _ from 'lodash'
  import Utils from '../utils'
  import LocaleMixin from '../locales/mixin'
  import Emitter from '../utils/emitter-mixin'
  import {sprintf} from 'sprintf-js'

  export default {
    name: 'DynamicFormErrorMessage',
    mixins: [LocaleMixin, Emitter],
    props: {
      error: Object
    },
    computed: {
      form () {
        return this.getDynamicForm()
      },
      commonClasses () {
        return (this.form && this.form.formSchema && this.form.formSchema.commonClasses) || {}
      },
      /*
      * 最近的具有model的组件（FormGroup或者DynamicForm）
      * */
      nmcComponent () {
        return this.findNMCParent()
      },
      /*
      * 上一层的Model，如果没有则等于formModel
      * */
      model () {
        return (this.nmcComponent && this.nmcComponent.model) || {}
      },
      formModel () {
        return (this.nmcComponent && this.nmcComponent.formModel) || {}
      },
      /*
      * errMsgStyle,
      * errMsgClass,
      * errMsgHidden // 是否隐藏，可为 function(model, formModel, field):boolean，默认 false
      * */
      field () {
        return (this.nmcComponent && this.nmcComponent.field) || {}
      },
      message () {
        if (this.error.errorTemplate) {
          return sprintf(this.error.errorTemplate, this.error.errorParams)
        }
        return this.lang('validation.' + Utils.toHumpType(this.error.rule), this.error.errorParams)
      },
      errMsgHidden () {
        if (!this.error || !this.error.rule) {
          return true
        }
        if (_.isNil(this.field.errMsgHidden)) {
          return false
        }
        if (_.isFunction(this.field.errMsgHidden)) {
          return this.field.errMsgHidden(this.model, this.formModel, this.field)
        }
        return !!this.field.errMsgHidden
      }
    }
  }
</script>
